Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

For example:

Given "aacecaaa", return "aaacecaaa".

Given "abcd", return "dcbabcd".

Solution:

  1. public class Solution {
  2. public String shortestPalindrome(String s) {
  3. String r = new StringBuilder(s).reverse().toString();
  4. int[] lps = getLPS(s + '|' + r);
  5. return r.substring(0, r.length() - lps[lps.length - 1]) + s;
  6. }
  7. // KMP get longest prefix and suffix count
  8. int[] getLPS(String s) {
  9. int[] lps = new int[s.length()];
  10. int i = 1, len = 0;
  11. while (i < s.length()) {
  12. if (s.charAt(i) == s.charAt(len)) lps[i++] = ++len;
  13. else if (len == 0) lps[i++] = 0;
  14. else len = lps[len - 1];
  15. }
  16. return lps;
  17. }
  18. }